package com.yejiarong.weather.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yejiarong.common.constant.CommonConstants;
import com.yejiarong.common.validate.ValidateUtils;
import com.yejiarong.weather.bean.dto.WeatherRegionCodeDto;
import com.yejiarong.weather.bean.entity.WeatherRegionCode;
import com.yejiarong.weather.mapper.IWeatherRegionCodeMapper;
import com.yejiarong.weather.service.IWeatherRegionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @author YeJR
 */
@Slf4j
@Service
public class WeatherRegionServiceImpl implements IWeatherRegionService {

    private final IWeatherRegionCodeMapper weatherRegionCodeMapper;

    public WeatherRegionServiceImpl(IWeatherRegionCodeMapper weatherRegionCodeMapper) {
        this.weatherRegionCodeMapper = weatherRegionCodeMapper;
    }

    /**
     * 查询城市的具体编码
     *
     * @param dto dto
     * @return 城市编码
     */
    @Override
    public String getRegionCode(WeatherRegionCodeDto dto) {
        ValidateUtils.valid(dto);

        if (StringUtils.isEmpty(dto.getCity())) {
            dto.setCity(dto.getProvince());
            dto.setCounty(dto.getCity());
        } else if (StringUtils.isEmpty(dto.getCounty())) {
            dto.setCounty(dto.getCity());
        }

        LambdaQueryWrapper<WeatherRegionCode> lambdaQueryWrapper = new LambdaQueryWrapper<WeatherRegionCode>()
                .eq(WeatherRegionCode::getProvince, dto.getProvince()).eq(WeatherRegionCode::getCity, dto.getCity())
                .eq(WeatherRegionCode::getCounty, dto.getCounty()).last(CommonConstants.LIMIT1);
        WeatherRegionCode weatherRegionCode = weatherRegionCodeMapper.selectOne(lambdaQueryWrapper);

        ValidateUtils.notNull(weatherRegionCode, "查询不到对应城市的天气编码");
        ValidateUtils.notBlank(weatherRegionCode.getCode(), "查询不到对应城市的天气编码");
        return weatherRegionCode.getCode();
    }
}
